#!/usr/bin/env python
#-*-coding:utf-8-*-
# ---------------------------------
# version:  1.0
#
# create-time:      <2008/12/12 00:17:07>
# last-update-time: <halida 03/05/2009 08:24:29>
# ---------------------------------
# module : filter

from qtlib import *
import entity,config,key

class EntityFilter(QWidget):
    """
    filter used for filting entity in the entity pool.
    """
    def __init__(self,pool,*args):
        QWidget.__init__(self,*args)
        #data
        self.file = config.get("tags")
        self.pool = pool
        self.list = []
        self.load()
        #component
        self.statusList = QListWidget(self)
        for tag in entity.STATUS:
            self.statusList.addItem(tag)
        self.statusList.setMaximumHeight(80)

        self.placeList = QListWidget(self)
        for tag in entity.PLACES:
            self.placeList.addItem(tag)
        self.placeList.setMaximumHeight(80)

        self.tagList = QListWidget(self)
        #self.tagList.setSelectionMode(QAbstractItemView.MultiSelection)
        #layout
        l = QVBoxLayout(self)
        l.addWidget(self.statusList)
        l.addWidget(self.placeList)
        l.addWidget(self.tagList,1)
        #event
        self.setAction()
        conn(self.placeList,"currentRowChanged(int)",self.select)
        conn(self.tagList,"currentRowChanged(int)",self.select)
        conn(self.statusList,"currentRowChanged(int)",self.select)

    def __del__(self):
        self.save()

    #---update---
    def refresh(self):
        logging.info("refresh filter:%s" , ",".join(self.list))
        self.tagList.clear()
        for tag in self.list:
            self.tagList.addItem(tag)
        self.statusList.setCurrentRow(0)
        self.tagList.setCurrentRow(0)
        self.placeList.setCurrentRow(0)
        self.select()

    def select(self,currentRow=None,tag=None):
        #select a tag
        if tag:
            index = self.list.index(tag)
            self.tagList.setCurrentRow(index)
            return
        #get tags
        status = entity.STATUS[self.statusList.currentRow()]
        place = entity.PLACES[self.placeList.currentRow()]
        tags = self.list[self.tagList.currentRow()]
        tags = set(tags.split(","))
        tags.add(status)
        tags.add(place)
        #remove ALL flag
        try:
            tags.remove(entity.ALL)
        except:
            pass
        self.selected(tags)

    def selected(self,tags):
        emit(self,"selected",tags)

    #---action---
    def setAction(self):
        #action list
        actions = (
            ("&Up"    ,self.tagUp    ,key.KEY_MOVE_UP),            
            ("&Down"  ,self.tagDown  ,key.KEY_MOVE_DOWN),            
            ("-"*20   ,lambda:None   ,None),
            ("&Add"   ,self.addTag   ,None),
            ("&Delete",self.deleteTag,None),
            ("&Select",self.selectTag,None),
            )
        #set
        self.tagList.setContextMenuPolicy(Qt.ActionsContextMenu)
        for title,func,shortcut in actions:
            action = QAction(title,self)
            if shortcut:
                action.setShortcut(shortcut)
            conn(action,"triggered()",func)
            self.tagList.addAction(action)

    def tagUp(self):
        """move up tag"""
        tag = self.currentTag()
        if not tag:return
        index = self.list.index(tag)
        if index<=0:return
        self.list[index]=self.list[index-1]
        self.list[index-1]=tag
        self.refresh()
        self.select(tag=tag)

    def tagDown(self):
        """move down tag"""
        tag = self.currentTag()
        if not tag:return
        index = self.list.index(tag)
        if index==len(self.list)-1:return
        self.list[index]=self.list[index+1]
        self.list[index+1]=tag
        self.refresh()
        self.select(tag=tag)

    def addTag(self):
        tag,ok = QInputDialog.getText(self,"","please input new tag:")
        if not ok:return
        tag = unicode(tag)
        if tag =="":return

        self.list.append(tag)
        self.refresh()

    def currentTag(self):
        row = self.tagList.currentRow()
        if row<0: return
        return self.list[row]

    def deleteTag(self):
        tag = self.currentTag()
        if not tag:return
        logging.info("delete tag:",tag)
        self.list.remove(tag)
        self.refresh()

    #---presistence---
    def save(self):
        output = open(self.file,'wb')
        output.write("\n".join(self.list))
        output.close()
        logging.info("tag list saving..")

    def load(self):
        try:
            output = open(self.file,'rb')
            data = output.read()
        except:
            data = ""

        if data =="":
            self.list = [u"work",u"study",u"fun",entity.ALL]
            return
        for line in data.splitlines():
            self.list.append(line)
        logging.info("tag list loading..")
    
    #---select tag---
    def selectTag(self):
        #select a tag
        tag,ok = QInputDialog.getText(self,"","please input tag:")
        tag = unicode(tag)
        if not ok:return
        self.selected(set([tag]))
